<?php
// +----------------------------------------------------------------------
// | 简易CMS
// +----------------------------------------------------------------------
// | Copyright (C) 2010 Hoping Software Studio.
// +----------------------------------------------------------------------
// | Version $Id: Member.php 25 2016-05-15 07:59:41Z IT果农 <htmambo@163.com> $
// +----------------------------------------------------------------------

namespace app\common\model;

use CMS\Model;

/**
 * 文档基础模型
 */
class Member extends Model {
    /* 用户模型自动完成 */

    protected $append = [
        'status_text', 'last_login_time_text', 'last_login_ip_text', 'sex_text', 'is_root'
    ];

    protected function getIsRootAttr($value, $data) {
        if(isset($data['uid'])) {
            return $data['uid'] = config('database.administrator_id')==$data['uid'];
        } else {
            return false;
        }
    }
    protected function getLastLoginTimeTextAttr($value, $data) {
        if (isset($data['last_login_time'])) {
            return date("Y-m-d H:i:s", $data['last_login_time']);
        } else {
            return '';
        }
    }

    protected function getStatusTextAttr($value, $data) {
        if (isset($data['status'])) {
            return get_status_title($data['status']);
        } else {
            return '';
        }
    }

    protected function getSexTextAttr($value, $data) {
        if (isset($data['sex'])) {
            return get_sex_title($data['sex']);
        } else {
            return '';
        }
    }

    protected function getLastLoginIpTextAttr($value, $data) {
        if (isset($data['last_login_ip'])) {
            return long2ip($data['last_login_ip']);
        } else {
            return '';
        }
    }

//    protected $_auto     = array(
//        array('login', 0, self::MODEL_INSERT),
//        array('password', 'user_md5', self::MODEL_BOTH_EXISTS, 'function'),
//        array('reg_ip', 'get_client_ip', self::MODEL_INSERT, 'function', 1),
//        array('reg_time', NOW_TIME, self::MODEL_INSERT),
//        array('last_login_ip', 0, self::MODEL_INSERT),
//        array('last_login_time', NOW_TIME, self::MODEL_INSERT),
//    );
//    protected $_validate = array(
//        /* 验证用户名 */
//        array('username', '5,30', '用户名长度为5-30个字符', self::EXISTS_VALIDATE, 'length'), //用户名长度不合法
//        array('username', '', '用户名已经存在', self::EXISTS_VALIDATE, 'unique'), //用户名被占用
//
//        /* 验证密码 */
//        array('password', '6,30', '密码长度为6-30个字符', self::EXISTS_VALIDATE, 'length'), //密码长度不合法
//        /* 验证昵称 */
//        array('nickname', '2,30', '昵称长度为2-30个字符', self::EXISTS_VALIDATE, 'length'),
//        //array('nickname', '', '昵称被占用', self::EXISTS_VALIDATE, 'unique'), //用户名被占用
//    );
    // 删除数据前的回调方法
    protected function _before_delete($options) {
        if (!$options['where']) {
            $this->error = '对不起，请指定要删除的用户！';
            return false;
        }
        $lists = $this->where($options['where'])->getField('uid', true);
        if (in_array(UID, $lists)) {
            $this->error = '对不起，就目前而言，我们不允许你去自杀！';
            return false;
        }
        return true;
    }

    /**
     * 用户登录认证
     * @param  string  $username 用户名
     * @param  string  $password 用户密码
     * @param  integer $type     用户名类型 （1-用户名，2-邮箱，3-手机，4-UID）
     * @return integer           登录成功-用户ID，登录失败-错误编号
     */
    public function login($username, $password = '', $type = 1, $enc = 1) {
        if (is_array($username)) {
            if (isset($username['password'])) {
                $password = $username['password'];
                $enc = 0;
            }
            if (isset($username['uid'])) {
                $username = $username['uid'];
                $type = 4;
            } else if (isset($username['email'])) {
                $username = $username['email'];
                $type = 2;
            } else if (isset($username['mobile'])) {
                $username = $username['mobile'];
                $type = 3;
            } else if (isset($username['username'])) {
                $username = $username['username'];
                $type = 1;
            } else {
                return 0;
            }
        }
        $map = array();
        switch ($type) {
            case 1:
                $map['username'] = $username;
                break;
            case 2:
                $map['email'] = $username;
                break;
            case 3:
                $map['mobile'] = $username;
                break;
            case 4:
                $map['uid'] = $username;
                break;
            default:
                return 0; //参数错误
        }
        if (!$password) {
            return 0;
        }
        if ($enc) {
            $password = user_md5($password);
        }
        /* 获取用户数据 */
        $user = $this->where($map)->find();
        if ($user) {
            $user = $user->toArray();
        }
        if (is_array($user)) {
            /* 验证用户密码 */
            if ($password === $user['password']) {
                /* 登录用户 */
                $this->autoLogin($user);
                return true;
            } else {
                $this->error = '密码错误！' . $password;
                return false;
            }
        }
        $this->error = '用户不存在或已被禁用！'; //应用级别禁用
        return false;
    }

    /**
     * 注销当前用户
     * @return void
     */
    public function logout() {
        session('user_auth', null);
        session('user_auth_sign', null);
    }

    /**
     * 自动登录用户
     * @param  integer $user 用户信息数组
     */
    private function autoLogin($user) {
        /* 更新登录信息 */
        $data = array(
            'uid'             => $user['uid'],
            'login'           => array('exp', '`login`+1'),
            'last_login_time' => NOW_TIME,
            'last_login_ip'   => get_client_ip(1),
        );
        if (NOW_TIME - $user['last_login_time'] > 1) {
            $this->save($data, array('uid' => $user['uid']));
            /* 记录登录SESSION和COOKIES */
            $auth = array(
                'uid'             => $user['uid'],
                'username'        => $user['username'],
                'nickname'        => $user['nickname'],
                //'group_id'        => $user['group_id'],
                //'client_id'       => $user['client_id'],
                'last_login_time' => $user['last_login_time'],
                    //'wid'             => $user['wid']
            );
        }

        session('user_auth', $auth);
        session('user_auth_sign', data_auth_sign($auth));
    }

    public function getNickName($uid) {
        return $this->where(array('uid' => (int) $uid))->getField('nickname');
    }

    /**
     * 注册一个新用户
     * @param  string $username 用户名
     * @param  string $password 用户密码
     * @param  int $groupId    用户组
     * @return integer          注册成功-用户信息，注册失败-错误编号
     */
    public function register($username, $password = '', $groupId = 0, $nickname = '', $wid = 0) {
        if (is_array($username)) {
            $data = $username;
        } else {
            $data = array(
                'username' => $username,
                'nickname' => $nickname ?: $username,
                'password' => $password,
                'group_id' => $groupId,
                'wid'      => $wid
            );
        }
        if (!$data['password']) {
            $this->error = '请填写密码！';
            return false;
        }
        /* 添加用户 */
        if ($this->create($data)) {
            $uid = $this->add();
            return $uid ? $uid : false; //0-未知错误，大于0-注册成功
        } else {
            return false; //错误详情见自动验证注释
        }
    }

    /**
     * 根据openid查询用户的信息
     * @param array $map
     * @param string $field 所需字段
     * @param string $unionid
     * @return array
     */
    public function getUserByOpenid($map, $field = '*') {
        $keys = array('openid', 'wid');
        foreach ($keys as $key) {
            if (!isset($map[$key]) || !$map[$key]) {
                $this->error = '参数错误！';
                return false;
            }
        }
        $arr = $this->where($map)->field($field)->find();
        return $arr;
    }

    /**
     * 递归生成用户名，用户第三方注册
     * @return string
     */
    public function makeUsername() {
        $username = 'CMS' . random(9, 1);         //生成一个随机的用户名
        $ret = $this->checkUserNameExist($username);
        if ($ret == 1) {
            return $this->makeUsername();
        } else {
            return $username;
        }
    }

    /*     * *
     * 判断用户名是否已被注册
     * @param $username
     * @return int 1 存在 其他 不存在
     * TODO 大于0：存在，等于0：不存在，小于0：参数错误
     */

    public function checkUserNameExist($username) {
        $map['username'] = $username;
        $ret = $this->where($map)->find();
        if ($ret) {
            return 1;
        }
        return 0;
    }

    public function updateInfo($uid, $password, $data = array()) {
        if (!$uid) {
            $this->error = '用户不存在！';
            return false;
        }
        if (!$password) {
            $this->error = '旧密码不正确！';
            return false;
        }
        if (isset($data['password']) && !$data['password']) {
            unset($data['password']);
        }
        if (!$data) {
            $this->error = '资源不完整！';
            return false;
        }
        $map = array('uid' => $uid);
        $info = $this->where($map)->find();
        if (!$info) {
            $this->error = '用户信息不存在！';
            return false;
        }
        if (md5($password) !== $info['password']) {
            $this->error = '旧密码不正确！';
            return false;
        }
        $data['password'] = md5($data['password']);
        $data = array_merge($info, $data);
        $result = $this->save($data, $map);
        if ($data['password']) {        //如果修改了密码则需要重新登录
            $this->logout();
        }
        return $result;
    }

}
